package com.hlxj.license.client.util;

import org.springframework.util.StringUtils;

import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @功能:【DateUtil 日期工具类】
 * @作者:代守诚
 * @日期:2019/5/15
 * @时间:16:28
 */
public class DateUtil {



    /**
     * 获取到期时间
     * @param time
     * @param addYear
     * @return
     */
    public static String getNewDateByYear(String time, Integer addYear) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        if(StringUtils.isEmpty(time)) {
            date = new Date();
        }else {
            try{
                date = dateFormat.parse(time);
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.YEAR, addYear);
        return dateFormat.format(calendar.getTime());
    }

    public static String getCurrentTime() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return simpleDateFormat.format(new Date());

    }

    /**
     * 转换成时间戳
     * @param time
     * @return
     */
    public static Long getTime(String time) {
        Long currentTime = null;
        SimpleDateFormat simpleDateFormat =   new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
        Date date;
        try {
            date = simpleDateFormat .parse(time);
            currentTime = date.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return currentTime;
    }

    public static String getNetWorkTime(String webUrl) {
        try {
            URL url = new URL(webUrl);
            URLConnection conn = url.openConnection();
            conn.connect();
            Long date = conn.getDate();
            Date dateTime = new Date(date);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return simpleDateFormat.format(dateTime);

        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String args[]) {
//        System.out.println(getTime("2010-11-13 12:00:00"));
//        System.out.println(getNewDateByYear(null, 3));
//        System.out.println(getNewDateByYear("", 3));
        System.out.println(getNewDateByYear("2010-11-13 12:00:00", 3));
//        System.out.println(Timestamp.valueOf(getNewDateByYear("2010-11-13 12:00:00", 3)));
//        System.out.println(getNewDate(String.valueOf(System.currentTimeMillis()), 3));
    }

}
